import React, { useState, useEffect } from "react";
import { Modal, Form, Input, Select, message, Button, Tag } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { useAppDispatch } from "../../../hooks/redux";
import { createProject } from "../../../store/projectSlice";
import { mockProjectApi } from "../../../api/mockProjectApi";
import type { User } from "../../../types/project";

const { TextArea } = Input;
const { Option } = Select;

interface CreateProjectModalProps {
  /** 弹窗是否可见 */
  visible: boolean;
  /** 取消回调 */
  onCancel: () => void;
  /** 成功创建回调 */
  onSuccess: () => void;
}

/**
 * 新建项目弹窗组件
 * 提供表单让用户输入项目信息并创建新项目
 */
const CreateProjectModal: React.FC<CreateProjectModalProps> = ({ visible, onCancel, onSuccess }) => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [groups, setGroups] = useState<Array<{ title: string; color: string }>>([
    { title: "待开始", color: "#f5f5f5" },
    { title: "进行中", color: "#1890ff" },
    { title: "已完成", color: "#52c41a" }
  ]);

  /**
   * 获取用户列表（用于负责人和参与人选择）
   */
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userList = await mockProjectApi.getUsers();
        setUsers(userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    };

    if (visible) {
      fetchUsers();
    }
  }, [visible]);

  /**
   * 处理表单提交
   * @param values 表单数据
   */
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      // 构建项目数据
      const projectData = {
        title: values.title,
        description: values.description,
        creator: users.find(u => u.id === values.creatorId) || users[0],
        members: values.memberIds?.map((id: string) => users.find(u => u.id === id)).filter(Boolean) || []
      };

      // 创建项目
      const newProject = await dispatch(createProject(projectData)).unwrap();

      // 如果有自定义分组，更新项目分组
      if (groups.length > 3 || groups.some((g, i) => g.title !== ["待开始", "进行中", "已完成"][i])) {
        // 这里可以添加更新分组的逻辑
        console.log("自定义分组:", groups);
      }

      message.success("项目创建成功");
      form.resetFields();
      setGroups([
        { title: "待开始", color: "#f5f5f5" },
        { title: "进行中", color: "#1890ff" },
        { title: "已完成", color: "#52c41a" }
      ]);
      onSuccess();
    } catch (error) {
      console.error("创建项目失败:", error);
      message.error("创建项目失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理弹窗关闭
   */
  const handleCancel = () => {
    form.resetFields();
    setGroups([
      { title: "待开始", color: "#f5f5f5" },
      { title: "进行中", color: "#1890ff" },
      { title: "已完成", color: "#52c41a" }
    ]);
    onCancel();
  };

  /**
   * 添加分组
   */
  const addGroup = () => {
    const newGroup = { title: "", color: "#f5f5f5" };
    setGroups([...groups, newGroup]);
  };

  /**
   * 删除分组
   */
  const removeGroup = (index: number) => {
    if (groups.length <= 1) {
      message.warning("至少需要保留一个分组");
      return;
    }
    const newGroups = groups.filter((_, i) => i !== index);
    setGroups(newGroups);
  };

  /**
   * 更新分组
   */
  const updateGroup = (index: number, field: string, value: string) => {
    const newGroups = [...groups];
    newGroups[index] = { ...newGroups[index], [field]: value };
    setGroups(newGroups);
  };

  /**
   * 预定义颜色选项
   */
  const colorOptions = [
    "#f5f5f5",
    "#1890ff",
    "#52c41a",
    "#faad14",
    "#f5222d",
    "#722ed1",
    "#13c2c2",
    "#eb2f96",
    "#fa541c",
    "#a0d911"
  ];

  return (
    <Modal
      title="新建项目"
      open={visible}
      onCancel={handleCancel}
      onOk={() => form.submit()}
      confirmLoading={loading}
      okText="创建项目"
      cancelText="取消"
      width={700}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          creatorId: users[0]?.id
        }}
      >
        {/* 项目标题 */}
        <Form.Item
          name="title"
          label="项目标题"
          rules={[
            { required: true, message: "请输入项目标题" },
            { max: 100, message: "标题不能超过100个字符" }
          ]}
        >
          <Input placeholder="请输入项目标题" />
        </Form.Item>

        {/* 项目描述 */}
        <Form.Item name="description" label="项目描述" rules={[{ max: 500, message: "描述不能超过500个字符" }]}>
          <TextArea placeholder="请输入项目描述（可选）" rows={3} showCount maxLength={500} />
        </Form.Item>

        {/* 负责人和参与人 */}
        <div className="flex gap-4">
          {/* 项目负责人 */}
          <Form.Item
            name="creatorId"
            label="项目负责人"
            className="flex-1"
            rules={[{ required: true, message: "请选择项目负责人" }]}
          >
            <Select placeholder="请选择负责人">
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  <div className="flex items-center gap-2">
                    <img src={user.avatar} alt={user.name} className="w-4 h-4 rounded-full" />
                    {user.name}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 参与人 */}
          <Form.Item name="memberIds" label="项目参与人" className="flex-1">
            <Select mode="multiple" placeholder="请选择参与人" allowClear maxTagCount={3}>
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  <div className="flex items-center gap-2">
                    <img src={user.avatar} alt={user.name} className="w-4 h-4 rounded-full" />
                    {user.name}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>
        </div>

        {/* 任务分组设置 */}
        <Form.Item label="任务分组设置">
          <div className="space-y-3">
            {groups.map((group, index) => (
              <div key={index} className="flex items-center gap-3 p-3 border border-gray-200 rounded-lg">
                <Input
                  placeholder="分组名称"
                  value={group.title}
                  onChange={e => updateGroup(index, "title", e.target.value)}
                  className="flex-1"
                />
                <Select
                  value={group.color}
                  onChange={value => updateGroup(index, "color", value)}
                  className="w-32"
                  dropdownRender={menu => (
                    <div>
                      {menu}
                      <div className="grid grid-cols-5 gap-2 p-2 border-t">
                        {colorOptions.map(color => (
                          <div
                            key={color}
                            className="w-6 h-6 rounded-full cursor-pointer border border-gray-200 hover:scale-110 transition-transform"
                            style={{ backgroundColor: color }}
                            onClick={() => updateGroup(index, "color", color)}
                          />
                        ))}
                      </div>
                    </div>
                  )}
                >
                  <Option value={group.color}>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-full" style={{ backgroundColor: group.color }} />
                      颜色
                    </div>
                  </Option>
                </Select>
                <Button
                  type="text"
                  icon={<DeleteOutlined />}
                  onClick={() => removeGroup(index)}
                  disabled={groups.length <= 1}
                  className="text-red-500 hover:text-red-700"
                />
              </div>
            ))}

            <Button type="dashed" icon={<PlusOutlined />} onClick={addGroup} className="w-full">
              添加分组
            </Button>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateProjectModal;
